package com.axx.android.profile.kettle;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.axx.android.LetterApp;
import com.axx.android.R;
import com.axx.android.base.BaseActivity;
import com.axx.android.common.BaseModel;
import com.axx.android.common.Constants;
import com.axx.android.common.SJRefreshView;
import com.axx.android.home.model.User;
import com.axx.android.letter.activity.RecipientActivity;
import com.axx.android.profile.auth.activity.LoginActivity;
import com.axx.android.utils.GsonUtils;
import com.axx.android.utils.HttpUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class KettleActivity extends BaseActivity {
    @Bind(R.id.tv_energy)
    TextView mTvEnergy;
    @Bind(R.id.btn_kettle)
    Button mBtnKettle;
    @Bind(R.id.tv_water_cnt)
    TextView mTvWaterCnt;
    @Bind(R.id.lv_list)
    RecyclerView mLvList;
    @Bind(R.id.activity_kettle)
    LinearLayout mActivityKettle;
    @Bind(R.id.layout_refresh)
    SJRefreshView layoutRefresh;
    private int curPage = 1;
    private int pageSize = 30;
    private int remainTime;
    private WaterLog log;
    private String btnText;

    private List<WaterLog.WaterLogBean> list = new ArrayList<>();
    private WaterLogAdapter waterLogAdapter;

    @Override
    public int getLayoutId() {
        return R.layout.activity_kettle;
    }

    private String target;

    @Override
    public void init(Bundle savedInstanceState) {
        target = getIntent().getStringExtra("target");
        initAdapter();
        layoutRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                curPage = 1;
                fetchWater();
            }
        });
    }

    private void initAdapter() {
        waterLogAdapter = new WaterLogAdapter(R.layout.view_item_water_log, list);
        mLvList.setAdapter(waterLogAdapter);
        mLvList.setLayoutManager(new LinearLayoutManager(this));
        waterLogAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                curPage++;
                fetchWater();
            }
        }, mLvList);
        waterLogAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                WaterLog.WaterLogBean logBean = (WaterLog.WaterLogBean) adapter.getData().get(position);
                String userString = GsonUtils.toJson(logBean.getFromUser());
                try {
                    User.UserListBean userListBean1 = GsonUtils.fromJson(userString, new TypeToken<User.UserListBean>() {
                    });

                    LatLng from = new LatLng(LetterApp.curLocation.getLatitude(), LetterApp.curLocation.getLongitude());
                    LatLng to = new LatLng(logBean.getFromUser().getLatitude(), logBean.getFromUser().getLongitude());

                    float distance = AMapUtils.calculateLineDistance(from, to);
                    String stringTime = String.format(Locale.US, "%.2f", distance / 1000);
                    userListBean1.setDistance(Double.parseDouble(stringTime));


                    Intent intent = new Intent(KettleActivity.this, RecipientActivity.class);
                    intent.putExtra("model", userListBean1);
                    startActivity(intent);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        layoutRefresh.post(new Runnable() {
            @Override
            public void run() {
                layoutRefresh.setRefreshing(true);
                fetchWater();
            }
        });

    }

    private void fetchWater() {
        HashMap<String, String> map = new HashMap<>();
        map.put("nowpage", curPage + "");
        map.put("pagenum", pageSize + "");
        map.put("fromUserId", LetterApp.authUser.getId());
        map.put("toUserId", target);
        HttpUtils.post(Constants.Url.Water.WATER_DETAIL, map, new HttpUtils.SJCallBack() {
            @Override
            public void onSuccess(String result) {
                layoutRefresh.setRefreshing(false);
                try {
                    BaseModel<WaterLog> logBaseModel = GsonUtils.fromJson(result, new TypeToken<BaseModel<WaterLog>>() {
                    });
                    if (logBaseModel.isSuccess()) {
                        showSuccess(logBaseModel);
                    } else {
                        showToast(logBaseModel.message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    showErrorParse();
                }
            }

            @Override
            public void onError() {
                showErrorNet();
                layoutRefresh.setRefreshing(false);
            }
        });
    }

    private void showSuccess(BaseModel<WaterLog> logBaseModel) {
        initHeader(logBaseModel);
        if (curPage == 1) {
            waterLogAdapter.setNewData(logBaseModel.data.getWaterLog());
            waterLogAdapter.disableLoadMoreIfNotFullPage(mLvList);
            waterLogAdapter.setEmptyView(R.layout.view_default_emtpy, mLvList);
        } else {
            int loadCount = logBaseModel.data.getWaterLog().size();
            waterLogAdapter.addData(logBaseModel.data.getWaterLog());
            if (loadCount < pageSize) {
                waterLogAdapter.loadMoreEnd();
            } else {
                waterLogAdapter.loadMoreComplete();
            }

        }
    }

    private void initHeader(BaseModel<WaterLog> logBaseModel) {
        log = logBaseModel.data;
        mTvEnergy.setText("邮票:" + logBaseModel.data.getMyEnerg());
        remainTime = logBaseModel.data.getRemainTime();


        btnText = "赠送邮票";
        if (LetterApp.authUser != null && LetterApp.authUser.getId().equals(target)) {
            btnText = "抽取邮票";
        }
        mBtnKettle.setText(btnText);
        if (logBaseModel.data.getRemainNumber() != 0) {
            mTvWaterCnt.setText("今日剩余" + logBaseModel.data.getRemainNumber() + "次" + btnText + "机会");
            if (logBaseModel.data.getRemainTime() > 1) {
                handler.postDelayed(runnable, 1000);
            }
        } else {
            mTvWaterCnt.setText("今日" + btnText + "机会用完了。明天再来吧");
        }

    }

    private Handler handler = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (remainTime < 1) {
                mBtnKettle.setText(btnText);
                handler.removeCallbacks(runnable);
            } else {
                remainTime = remainTime - 1;
                mBtnKettle.setText("剩余" + "(" + remainTime + ")");
                handler.postDelayed(runnable, 1000);
            }
        }
    };

    @Override
    protected void onPause() {
        super.onPause();
        handler.removeCallbacks(runnable);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick(R.id.btn_kettle)
    public void onViewClicked() {
        if (LetterApp.authUser == null) {
            startActivity(new Intent(this, LoginActivity.class));
            return;
        }
        fetchWaterAction();
    }

    private void fetchWaterAction() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("fromUserId", LetterApp.authUser.getId());
        hashMap.put("toUserId", target);
        hashMap.put("token", LetterApp.authUser.getToken());
        hashMap.put("energy", log.getMyEnerg() + "");
        HttpUtils.post(Constants.Url.Water.WATER_ACTION, hashMap, new HttpUtils.SJCallBack() {
            @Override
            public void onSuccess(String result) {
                try {
                    BaseModel baseModel = GsonUtils.fromJson(result, new TypeToken<BaseModel>() {
                    });
                    if (baseModel.isSuccess()) {
                        showToast(btnText + "成功");
                        fetchWater();
                    } else {
                        showToast(baseModel.message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    showErrorParse();
                }
            }

            @Override
            public void onError() {
                showErrorNet();
            }
        });
    }
}
